package top.vanchor.myblog2back.controller.user;


import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import top.vanchor.myblog2back.config.JwtConfigProperties;
import top.vanchor.myblog2back.entity.BlogBlog;
import top.vanchor.myblog2back.service.IBlogBlogService;
import top.vanchor.myblog2back.service.IBlogSubscribeService;
import top.vanchor.myblog2back.service.IBlogUserService;
import top.vanchor.myblog2back.utils.JWTUtils;
import top.vanchor.myblog2back.utils.JwtInterceptor;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Ding
 * @since 2021-11-12
 */
@CrossOrigin
@RestController
@RequestMapping("/blogBlog")
public class BlogBlogController {
    @Resource
    IBlogBlogService iBlogBlogService;
    @Resource
    IBlogSubscribeService subscribeService;
    @Autowired
    private JwtConfigProperties jwtConfigProperties;

    @ApiOperation("获取所有博客--可搜索根据条件")
    @PostMapping("/getSearchBlogJson")
    @ResponseBody
    public JSONObject getSearchBlogJson(@RequestBody JSONObject data){
        JSONObject jsonObject = new JSONObject();
        JSONObject jsonData = new JSONObject();
        Integer index = Integer.parseInt(String.valueOf(data.get("pageNum")));
        Integer num = Integer.parseInt(String.valueOf(data.get("num")));
        //''加载所有，否则就模糊查询
        String searchText = String.valueOf(data.get("searchText"));
        //0：所有正常用户。else，只检索当前id用户的博客
        Integer uId = Integer.parseInt(String.valueOf(data.get("uId")));
        //1：本人（加载所有）。2：所有人（加载非私密）。3：用户的关注
        Integer type = Integer.parseInt(String.valueOf(data.get("type")));
        List<Integer> starIds = new ArrayList<>();
        PageInfo<Map<String,Object>> list = new PageInfo<>();
        try {
            if (type.equals(3)){
                //用户查询“我的关注”-不包括本人
                Integer userId = Integer.valueOf(JWTUtils.getUserId(String.valueOf(data.get("token"))));
                starIds = subscribeService.getStarIdsByUserId(userId);
                System.err.println(starIds);
            }
            list = iBlogBlogService.getSearchBlogJson(index,num,searchText,uId,type,starIds);
            jsonData.put("blogs",list.getList());
            jsonData.put("total",list.getTotal());
            jsonData.put("index",list.getPageNum());
            jsonData.put("num",list.getSize());
            jsonObject.put("data",jsonData);
            jsonObject.put("code",200);
            jsonObject.put("msg","ok");
        }catch (Exception e){
            e.printStackTrace();
            jsonObject.put("code",500);
            jsonObject.put("msg","服务器异常，请求失败");
        }
        return jsonObject;
    }


    @ApiOperation("获取博客详情byBlogId")
    @PostMapping("/getBlogByBlogId")
    @ResponseBody
    public JSONObject getBlogByBlogId(@RequestBody JSONObject data){
        JSONObject jsonObject = new JSONObject();
        JSONObject jsonDemo = new JSONObject();
        Integer blog_id = Integer.parseInt(String.valueOf(data.get("blogId")));
        //获取该博客基本信息
        List<Map<String,Object>> listdemo = iBlogBlogService.getBlogById(blog_id, "-1".equals(String.valueOf(data.get("token")))?-1:Integer.valueOf(JWTUtils.getUserId(String.valueOf(data.get("token")))));
        Map<String,Object> demo = listdemo.size() == 0? new HashMap<>(0) : listdemo.get(0);
        demo.put("blog_json_nav", JSONArray.parse(String.valueOf(demo.get("blog_nav"))));

        if (listdemo.size()>0){
            /**
             * 判断状态是否为2--私密
             * 不是本人访问普通链接不能查看
             */
            if (String.valueOf(listdemo.get(0).get("blog_status")).equals("2")){
                //进一步验证是否是本人
                Integer uId = -1;
                if (!String.valueOf(data.get("token")).equals("-1")){
                    uId = Integer.valueOf(JWTUtils.getUserId(String.valueOf(data.get("token"))));
                }
                if (uId!=Integer.parseInt(String.valueOf(listdemo.get(0).get("blog_author_id")))){
                    //不是本人，不能传回博客
                    jsonDemo.put("blog", "");
                    jsonObject.put("data","");
                    jsonObject.put("code",430);
                    jsonObject.put("msg","此文被设为私密，你无权查看！");
                }else{
                    jsonDemo.put("blog",listdemo.get(0));
                    jsonObject.put("data",jsonDemo);
                    jsonObject.put("code",200);
                    jsonObject.put("msg","加载成功");
                }
            }else{
                jsonDemo.put("blog",demo);
                jsonObject.put("data",jsonDemo);
                jsonObject.put("code",200);
                jsonObject.put("msg","加载成功");
            }
        }else{
            jsonDemo.put("blog", "");
            jsonObject.put("data","");
            jsonObject.put("code",420);
            jsonObject.put("msg","此博客不存在或已被删除");
        }

        return jsonObject;
    }

    @ApiOperation("发布博客")
    @RequestMapping("/toCreateBlog")
    @ResponseBody
    public JSONObject toCreateBlog(@RequestBody JSONObject dt){
        JSONObject data = dt.getJSONObject("form");
        JSONObject jsonObject = new JSONObject();
        BlogBlog blogBlog = new BlogBlog();
        blogBlog.setBlogTitle(String.valueOf(data.get("title")));
        blogBlog.setBlogContent(String.valueOf(data.get("content")));
        blogBlog.setBlogAuthorId(Integer.parseInt(String.valueOf(data.get("uid"))));
        blogBlog.setBlogMainImg(String.valueOf(data.get("img")));
        blogBlog.setBlogCreateDateTime(LocalDateTime.now());
        blogBlog.setBlogViewNum(0);
        if (iBlogBlogService.toCreateBlog(blogBlog) > 0){
            jsonObject.put("code",200);
        }else{
            jsonObject.put("code",500);
        }
        return jsonObject;
    }


    @ApiOperation("编辑博客")
    @RequestMapping("/toUpdateBlog")
    @ResponseBody
    public JSONObject toUpdateBlog(@RequestBody JSONObject dt){
        JSONObject data = dt.getJSONObject("form");
        JSONObject jsonObject = new JSONObject();
        BlogBlog blogBlog = new BlogBlog();
        blogBlog.setBlogId(Integer.parseInt(String.valueOf(dt.get("blogId"))));
        blogBlog.setBlogTitle(String.valueOf(data.get("title")));
        blogBlog.setBlogContent(String.valueOf(data.get("content")));
        blogBlog.setBlogMainImg(String.valueOf(data.get("img")));
        if (iBlogBlogService.toUpdateBlog(blogBlog) >= 0){
            jsonObject.put("code",200);
        }else{
            jsonObject.put("code",500);
        }
        return jsonObject;
    }

    @ApiOperation("删除博客")
    @RequestMapping("/toDelBlogById")
    @ResponseBody
    public JSONObject toDelBlogById(@RequestBody JSONObject data){
        JSONObject jsonObject = new JSONObject();
        if (iBlogBlogService.toDelBlogById(Integer.parseInt(String.valueOf(data.get("blog_id")))) > 0){
            jsonObject.put("code",200);
        }else{
            jsonObject.put("code",500);
            jsonObject.put("msg","服务器异常，操作失败");
        }
        return jsonObject;
    }

    @ApiOperation("隐藏/私密博客")
    @RequestMapping("/hiddenBlogById")
    @ResponseBody
    public JSONObject hiddenBlogById(@RequestBody JSONObject data){
        JSONObject jsonObject = new JSONObject();
        if (iBlogBlogService.hiddenBlogById(Integer.parseInt(String.valueOf(data.get("blog_id"))),Integer.parseInt(String.valueOf(data.get("type")))) > 0){
            jsonObject.put("code",200);
        }else{
            jsonObject.put("code",500);
            jsonObject.put("msg","服务器异常，操作失败");
        }
        return jsonObject;
    }

    @ApiOperation("点赞/取赞博客")
    @RequestMapping("/toLikeOrUnlikeBlog")
    @ResponseBody
    public JSONObject toLikeOrUnlikeBlog(@RequestBody JSONObject data){
        JSONObject jsonObject = new JSONObject();
        Integer blogId = Integer.parseInt(String.valueOf(data.get("blog_id")));
        Integer type = Integer.parseInt(String.valueOf(data.get("type")));
        Integer uId = Integer.parseInt(String.valueOf(data.get("uId")));
        if (iBlogBlogService.toLikeOrUnlikeBlog(blogId,type,uId) > 0){
            jsonObject.put("code",200);
        }else{
            jsonObject.put("code",500);
            jsonObject.put("msg","服务器异常，操作失败");
        }
        return jsonObject;
    }

    @ApiOperation("公开博客")
    @RequestMapping("/noHiddenBlogById")
    @ResponseBody
    public JSONObject noHiddenBlogById(@RequestBody JSONObject data){
        JSONObject jsonObject = new JSONObject();
        if (iBlogBlogService.noHiddenBlogById(Integer.parseInt(String.valueOf(data.get("blog_id")))) > 0){
            jsonObject.put("code",200);
            jsonObject.put("msg","博客公开成功");
        }else{
            jsonObject.put("code",500);
            jsonObject.put("msg","服务器异常，操作失败");
        }
        return jsonObject;
    }

    @ApiOperation("浏览博客")
    @RequestMapping("/addViewTime")
    @ResponseBody
    public JSONObject addViewTime(@RequestBody JSONObject data){
        JSONObject jsonObject = new JSONObject();
        if (iBlogBlogService.addViewTime(Integer.parseInt(String.valueOf(data.get("blogId")))) > 0){
            jsonObject.put("code",200);
            jsonObject.put("msg","成功");
        }else{
            jsonObject.put("code",500);
            jsonObject.put("msg","请求异常");
        }
        return jsonObject;
    }

    @ApiOperation("编辑博客内导航")
    @RequestMapping("/editBlogNav")
    @ResponseBody
    public JSONObject editBlogNav(@RequestBody BlogBlog data){
        JSONObject jsonObject = new JSONObject();
        System.err.println(data);
        if (iBlogBlogService.editBlogNav(data) > 0 ){
            jsonObject.put("code",200);
            jsonObject.put("msg","编辑成功");
        }else{
            jsonObject.put("code",500);
            jsonObject.put("msg","请求异常");
        }
        return jsonObject;
    }
}
